package managedbeans;

import entities.Forumposts;
import entities.Forumthreads;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import langresources.ResourcesController;
import utils.dataaccess.DBInterface;


@ManagedBean(name="newThreadBean")
@SessionScoped
public class NewThreadBean  extends GenericForumBean implements Serializable{

    private Forumthreads newThread;
    private String title;
    private String text;
    
    public NewThreadBean() {

        currentBlock = getCurrentBlock();
        System.out.println(currentBlock.getName());
        newThread = new Forumthreads();
    }
    
    public String createThread(String author){

        if(author.equals("") || author==null){
            showMessage(ResourcesController.extractResource("MESSAGE.ACCESS_DENIED"), ResourcesController.extractResource("USER_NOT_AUTHORIZED"));
        } else {       
            currentBlock = getCurrentBlock();
            newThread.setAuthor(author);
            newThread.setBid((int)currentBlock.getId());
            newThread.setId(generateID());
            newThread.setName(title);
            newThread.setPostsnumber(0);
            DBInterface.save(newThread);
            leaveComment(author);
        }
        return "/threads.xhtml?faces-redirect=true";
    }

    public void leaveComment(String author){

        if(author.equals("") || author==null){
            showMessage(ResourcesController.extractResource("MESSAGE.ACCESS_DENIED"), ResourcesController.extractResource("USER_NOT_AUTHORIZED"));
        } else {
            Forumposts newPost = new Forumposts();
            newPost.setAuthor(author);
            newPost.setRate(0d);
            newPost.setText(text);
            newPost.setTid((int)newThread.getId());
            newPost.setDatetime(getTimestamp());
            newPost.setId(generateID());
            DBInterface.save(newPost);
            text = "";
            showMessage(ResourcesController.extractResource("MESSAGE.INFO"),ResourcesController.extractResource("THREAD_CREATED"));
        }
    }
    
    // GETTERS-SETTERS

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }  
}
